package com.saicmotor.paging;

import androidx.annotation.NonNull;
import androidx.paging.PageKeyedDataSource;

import com.saicmotor.paging.Bean.Api;
import com.saicmotor.paging.Bean.DataBean;

import java.util.List;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * @Author xinxinzhang
 * @Date 2022/08/17
 **/
public class PagingDataSource extends PageKeyedDataSource<String, DataBean.ResultBean> {
    // 网络数据使用PageKeyedDataSource更合适

    private static final String TAG = PagingDataSource.class.getSimpleName();
    private int mPage = 1;

    @Override
    public void loadInitial(@NonNull LoadInitialParams<String> params, @NonNull final LoadInitialCallback<String, DataBean.ResultBean> callback) {
        Api api = RetrofitClient.getInstance().createApi(Api.class);
        Call<List<DataBean.ResultBean>> call = api.getArticleList1(mPage);
        call.enqueue(new Callback<List<DataBean.ResultBean>>() {
            @Override
            public void onResponse(Call<List<DataBean.ResultBean>> call, Response<List<DataBean.ResultBean>> response) {
                if (response.isSuccessful() && response.code() == 200) {
                    List<DataBean.ResultBean> data  = response.body();
                    callback.onResult(data, "before", "after");
                }

            }

            @Override
            public void onFailure(Call<List<DataBean.ResultBean>> call, Throwable t) {
            }
        });
    }

    //加载上一页
    @Override
    public void loadBefore(@NonNull LoadParams<String> params, @NonNull LoadCallback<String, DataBean.ResultBean> callback) {
    }

    //加载下一页
    @Override
    public void loadAfter(@NonNull final LoadParams<String> params, @NonNull final LoadCallback<String, DataBean.ResultBean> callback) {
        mPage++;
        Api api = RetrofitClient.getInstance().createApi(Api.class);
        Call<List<DataBean.ResultBean>> call = api.getArticleList1(mPage);
        call.enqueue(new Callback<List<DataBean.ResultBean>>() {
            @Override
            public void onResponse(Call<List<DataBean.ResultBean>> call, Response<List<DataBean.ResultBean>> response) {
                if (response.isSuccessful() && response.code() == 200) {
                    List<DataBean.ResultBean> data  = response.body();
                    callback.onResult(data, params.key);
                }
            }

            @Override
            public void onFailure(Call<List<DataBean.ResultBean>> call, Throwable t) {
            }
        });
    }
}
